#!/usr/bin/env python3
"""
验证依赖图功能修改是否正确的脚本
"""

import os
import re
import sys

def check_backend_changes():
    """检查后端修改"""
    print("🔍 检查后端修改...")
    
    view_file = "myapp/views/view_train_model.py"
    if not os.path.exists(view_file):
        print(f"❌ 文件不存在: {view_file}")
        return False
    
    with open(view_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 检查action装饰器是否移除了确认文本
    action_pattern = r'@action\("view_dependency_graph",\s*"查看依赖图",\s*"",\s*"fa-sitemap"'
    if re.search(action_pattern, content):
        print("✅ action装饰器确认文本已移除")
    else:
        print("❌ action装饰器确认文本未正确移除")
        return False
    
    # 检查方法是否返回JSON数据
    if 'return self.response(200, data=response_data' in content:
        print("✅ 方法已修改为返回JSON数据")
    else:
        print("❌ 方法未正确修改为返回JSON数据")
        return False
    
    # 检查是否包含模型信息和统计信息
    if 'model_info' in content and 'statistics' in content:
        print("✅ 包含模型信息和统计信息")
    else:
        print("❌ 缺少模型信息或统计信息")
        return False
    
    return True

def check_frontend_changes():
    """检查前端修改"""
    print("\n🔍 检查前端修改...")
    
    frontend_file = "myapp/frontend/src/pages/ADUGTemplate.tsx"
    if not os.path.exists(frontend_file):
        print(f"❌ 文件不存在: {frontend_file}")
        return False
    
    with open(frontend_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 检查是否立即显示弹出框
    if 'setVisableDependencyGraph(true)' in content:
        print("✅ 立即显示弹出框逻辑已添加")
    else:
        print("❌ 缺少立即显示弹出框逻辑")
        return False
    
    # 检查是否有响应状态处理
    if 'dependencyGraphData.success' in content:
        print("✅ 响应状态处理已添加")
    else:
        print("❌ 缺少响应状态处理")
        return False
    
    # 检查是否有模型信息显示
    if 'model_info' in content and 'statistics' in content:
        print("✅ 模型信息和统计信息显示已添加")
    else:
        print("❌ 缺少模型信息或统计信息显示")
        return False
    
    # 检查是否有当前模型标识
    if 'is_current' in content:
        print("✅ 当前模型标识已添加")
    else:
        print("❌ 缺少当前模型标识")
        return False
    
    return True

def check_test_files():
    """检查测试文件"""
    print("\n🔍 检查测试文件...")
    
    test_files = [
        "myapp/test_dependency_graph.html",
        "myapp/test_dependency_api.py",
        "myapp/DEPENDENCY_GRAPH_CHANGES.md"
    ]
    
    all_exist = True
    for file_path in test_files:
        if os.path.exists(file_path):
            print(f"✅ {file_path} 存在")
        else:
            print(f"❌ {file_path} 不存在")
            all_exist = False
    
    return all_exist

def check_action_logic():
    """检查action逻辑"""
    print("\n🔍 检查action处理逻辑...")
    
    frontend_file = "myapp/frontend/src/pages/ADUGTemplate.tsx"
    if not os.path.exists(frontend_file):
        return False
    
    with open(frontend_file, 'r', encoding='utf-8') as f:
        content = f.read()
    
    # 检查是否有特殊处理view_dependency_graph的逻辑
    pattern = r'if\s*\(\s*action\.name\s*===\s*[\'"]view_dependency_graph[\'"]'
    if re.search(pattern, content):
        print("✅ view_dependency_graph特殊处理逻辑存在")
        
        # 检查是否直接调用handleViewDependencyGraph
        if 'handleViewDependencyGraph(modelId)' in content:
            print("✅ 直接调用handleViewDependencyGraph")
            return True
        else:
            print("❌ 未直接调用handleViewDependencyGraph")
            return False
    else:
        print("❌ 缺少view_dependency_graph特殊处理逻辑")
        return False

def main():
    """主函数"""
    print("🚀 开始验证依赖图功能修改")
    print("=" * 60)
    
    checks = [
        ("后端修改", check_backend_changes),
        ("前端修改", check_frontend_changes),
        ("测试文件", check_test_files),
        ("Action逻辑", check_action_logic)
    ]
    
    results = []
    for name, check_func in checks:
        try:
            result = check_func()
            results.append((name, result))
        except Exception as e:
            print(f"❌ {name}检查时发生错误: {e}")
            results.append((name, False))
    
    # 汇总结果
    print("\n📋 验证结果汇总:")
    print("=" * 60)
    
    success_count = 0
    for name, result in results:
        status = "✅" if result else "❌"
        print(f"{status} {name}: {'通过' if result else '失败'}")
        if result:
            success_count += 1
    
    total_count = len(results)
    print(f"\n总检查项: {total_count}")
    print(f"通过项: {success_count}")
    print(f"失败项: {total_count - success_count}")
    print(f"通过率: {success_count/total_count*100:.1f}%")
    
    if success_count == total_count:
        print("\n🎉 所有检查项都通过！修改应该已经生效。")
        print("\n📝 下一步:")
        print("1. 重启应用服务器")
        print("2. 清除浏览器缓存")
        print("3. 测试依赖图功能")
        return True
    else:
        print(f"\n⚠️  有 {total_count - success_count} 个检查项失败，请检查修改。")
        return False

if __name__ == "__main__":
    success = main()
    sys.exit(0 if success else 1)
